import { fetchImages } from '../utils/getCrawlImg'
import { getFiles } from '../utils/getFiles'

let dir = ''
export const event = (app, mainWindow, ipcMain, dialog) => {
  // 选择图片保存路径
  ipcMain.on('choose-save-dir', () => {
    dialog
      .showOpenDialog(mainWindow, {
        properties: ['openDirectory'],
      })
      .then((result) => {
        if (!result.canceled) {
          dir = result.filePaths[0]
          mainWindow.webContents.send('choose-dir', result.filePaths[0])
        }
      })
  })

  // 爬取网站图片
  ipcMain.handle('save', (_, res1) => {
    if (dir === '') {
      mainWindow.webContents.send('no-dir')
      return
    }
    fetchImages(
      res1,
      dir,
      // 爬取到的
      (len) => {
        mainWindow.webContents.send('image-num', len)
      },
      // 已经保存的
      async () => {
        try {
          const files = await getFiles(dir)
          mainWindow.webContents.send('save-image', files)
        } catch (e) {
          return e
        }
      },
      // 开始爬取
      () => {
        mainWindow.webContents.send('start-image')
      },
      // 爬取错误
      () => {
        mainWindow.webContents.send('error-image')
      },
    )
  })

  // 右上角app控件
  // 最小化app
  ipcMain.on('retract-app', () => {
    mainWindow.minimize()
  })
  // 放大app
  ipcMain.on('amplify-app', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.restore()
    } else {
      mainWindow.maximize()
    }
  })
  // 关闭app
  ipcMain.on('stop-app', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })
}
